package Midium;

import java.util.Arrays;
//看了答案以后，改进思路：不要引入绝对值
public class Solution16_2 {
    public static int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int minDis = Integer.MAX_VALUE;
        int sum=0;
        for(int i = 0 ; i < nums.length-2;i++){
            int j = i+1;
            int k = nums.length-1;
            while (j<k){
                //如果a+b+c>=target 则k--；如果a+b+c<target 则j++
                int a = nums[i],b=nums[j],c=nums[k];
                if(a+b+c==target)
                    return target;
                //更新最小值
                int dis = Math.abs(target-a-b-c);
                if(dis<minDis){
                    minDis=dis;
                    sum=a+b+c;
                }
                if(a+b+c>=target)
                    k--;
                else
                    j++;
            }
        }
        return sum;
    }
}
